import axios from "axios";
// import router from "../router";

const http = axios.create({
  baseURL: 'http://47.114.72.133:8088/insurance_war',
  timeout:1000
})


//请求拦截
http.interceptors.request.use(function (config) {//正常
  // config 是请求参数配置
  // 如果本地有 token 就应该发送给后端，格式如下
  let token = store.state.userStore.token;
  console.log('请求头', token);

  if (token) {
    // config.headers['token'] = token;

    // config.headers['Authorization'] = 'Bearer ' + token;
  }
  // Do something before request is sent
  //比如在这里显示 loading 
  return config;
}, function (error) {//错误
  // Do something with request error
  return Promise.reject(error);
});
//响应拦截
http.interceptors.response.use(function (response,) {//正常响应 200 一类的
  //将服务器返回的最新token 更新
  if (response.data.token) {
    store.dispatch('userStore/setTokenActions', response.data.token)
  }

  return response;
}, function (error) {//响应失败 -统一处理所有失败
  switch (error.response.status) {
    case 401:
      return router.push({
        path: '/login',
        query: { // 记录原来想访问的路径，下次登录成功后直接跳转到该路径
          redirect: router.currentRoute.fullPath
        }
      });
    case 408:
      return console.log('请求超时');
    case 500:
      return console.log('服务器端出错');
  }
  //比如：取消loading
  //比如：没有权限则返回登录页
  // Do something with response error
  return Promise.reject(error);
});

export default http;
